package com.hopes.bizz.close.position.support;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hopes.bizz.close.position.dto.HazardCachePositionDTO;
import com.hopes.bizz.close.position.service.HazardCachePositionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yumr
 * @ProjectName bizz
 * @time 2024/2/1 14:40
 */
@Component
@RequiredArgsConstructor
public class TempMockGpsPositionTimer implements InitializingBean {

    private final HazardCachePositionService hazardCachePositionService;

    private final Integer indexMax = 100;
    private final AtomicInteger index  = new AtomicInteger(1);

    final ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(1);

    final JSONArray positionArr = JSON.parseArray("[\n" +
            "    {\n" +
            "        \"long\":\"117.61987060465387\",\n" +
            "        \"lat\":\"37.67217872704944\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"long\":\"117.6198060465387\",\n" +
            "        \"lat\":\"37.67218872704944\"\n" +
            "    }\n" +
            "]");

    @Override
    public void afterPropertiesSet() throws Exception {
        threadPoolExecutor.scheduleWithFixedDelay(() -> {

            System.out.println("Thread Name : "
                    + Thread.currentThread().getName() + "  i am a task : date ->  "
                    + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            final HazardCachePositionDTO positionDTO = new HazardCachePositionDTO();
            positionDTO.setDeviceNo("2121");
            positionDTO.setDataTime(Calendar.getInstance().getTime());
            final JSONObject jsonObject = positionArr.getJSONObject(index.getAndIncrement() % 2);
            positionDTO.setLongitude(MapUtil.getStr(jsonObject, "long"));
            positionDTO.setLatitude(MapUtil.getStr(jsonObject, "lat"));
            positionDTO.setSpeed(1.2);
            hazardCachePositionService.locations(positionDTO);

            if (index.get() == indexMax) {
                index.set(1);
            }
        }, 5, 5, TimeUnit.SECONDS);

    }
}
